#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<string.h>
#include <pthread.h>

struct serverData
{
    int sockfd;
    sockaddr_in server;
    socklen_t len;
};

void Usage(char *proc)
{
    std::cout << "\nUsage:" << proc << " serverip"
              << " serverport" << std::endl;
}

void *Sendmessage(void *argv)
{
    serverData *ser = static_cast<serverData *>(argv);

    while (1)
    {
        std::string message;
        std::cerr << "please Enter#";
        getline(std::cin, message);
        int ns = sendto(ser->sockfd, message.c_str(), message.size(), 0, (const sockaddr *)&ser->server, ser->len);
    }
}

void *Recvmessage(void *argv)
{
    serverData *ser = static_cast<serverData *>(argv);
    // 解耦合
    char buf[1024];
    while (1)
    {
        struct sockaddr_in temp;
        socklen_t len_t = sizeof(temp);
        int n = recvfrom(ser->sockfd, buf, sizeof(buf), 0, (sockaddr *)&temp, &len_t);
        if (n > 0)
        {
            buf[n] = 0;
            std::cout << buf << std::endl;
            memset(buf,0,sizeof(buf));
        }
        //memset(buf,0,sizeof(buf));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    socklen_t len = sizeof(server);
    bzero(&server, len);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    // server.sin_addr.s_addr =htonl(inet_addr(serverip.c_str()));//为什么错误
    // std::cout<<server.sin_addr.s_addr <<std::endl;

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socker error" << std::endl;
        return 1;
    }

    serverData Data;
    Data.server = server;
    Data.sockfd = sockfd;
    Data.len = len;

    pthread_t send;
    pthread_t recv;
    pthread_create(&send, nullptr, Sendmessage, &Data);
    pthread_create(&recv, nullptr, Recvmessage, &Data);

    pthread_join(send, nullptr);
    pthread_join(recv, nullptr);

    close(sockfd);

    return 0;
}